package com.kika.obwiki.job;

import com.kika.obwiki.service.IEbookSnapshotService;
import com.kika.obwiki.utils.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 电子书快照定时任务
 * 每分钟自动生成今日电子书快照
 *
 * @author cr
 * @since 2025-06-22
 */
@Component
public class EbookSnapshotJob {
  private static final Logger LOG = LoggerFactory.getLogger(EbookSnapshotJob.class);

  @Resource
  private IEbookSnapshotService ebookSnapshotService;

  @Resource
  private SnowFlake snowFlake;

  /**
   * 每分钟执行一次快照生成任务
   * 只有等上一次执行完成，下一次才会在下一个时间点执行，错过就错过
   * 日志流水号便于排查问题
   */
  @Scheduled(cron = "0 0/1 * * * ?")
  public void doSnapshot() {
    // 增加日志流水号
    MDC.put("LOG_ID", String.valueOf(snowFlake.nextId()));
    LOG.info("生成今日电子书快照开始");
    Long start = System.currentTimeMillis();
    ebookSnapshotService.genSnapshot();
    LOG.info("生成今日电子书快照结束，耗时：{}毫秒", System.currentTimeMillis() - start);
  }
}